<template>
  <dys-modal
    :open="open"
    :title="t('localeManagement')"
    @cancel="emit('cancel')"
    @ok="handleSubmit"
    :width="400"
  >
    <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
      <a-form-item :label="t('国际化Key值')" v-bind="validateInfos.localeKey">
        <a-input
          v-model:value="modelRef.localeKey"
          :placeholder="t('Please enter the international K value')"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item :label="t('chinese')" v-bind="validateInfos['zh-CN']">
        <a-input
          v-model:value="modelRef['zh-CN']"
          :placeholder="t('Please enter Chinese')"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item :label="t('english')" v-bind="validateInfos['en-US']">
        <a-input
          v-model:value="modelRef['en-US']"
          :placeholder="t('Please enter English')"
          allow-clear
        ></a-input>
      </a-form-item>
    </a-form>
  </dys-modal>
</template>
<script lang="ts" setup>
import { add, update } from "@/api/system/locale";
import type { LocaleParams, QueryPageResult } from "@/api/system/locale/typing";
import type { FormRule } from "@/typing";
import { Form, message } from "ant-design-vue";
import { pick } from "lodash";
import { reactive, watch } from "vue";
import { useI18n } from "vue-i18n";
interface Props {
  /**弹窗 */
  open: boolean;
  /**行数据 */
  model: QueryPageResult;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "ok"]);
const { t } = useI18n();
const initValue = (): LocaleParams => ({
  localeId: null,
  localeKey: null,
  "zh-CN": null,
  "en-US": null,
});
const modelRef = reactive(initValue());
const modelRule = reactive<FormRule<LocaleParams>>({
  localeKey: [
    {
      required: true,
      message: () => t("Please enter the international K value"),
    },
  ],
  "zh-CN": [
    {
      required: true,
      message: () => t("Please enter Chinese"),
    },
  ],
  "en-US": [
    {
      required: true,
      message: () => t("Please enter English"),
    },
  ],
});
const { validate, validateInfos, resetFields } = Form.useForm(
  modelRef,
  modelRule
);
watch([() => props.model, () => props.open], ([model]) => {
  resetFields(pick(model, Object.keys(modelRef)) || initValue());
});
/**提交 */
const handleSubmit = async () => {
  try {
    await validate();
  } catch {
    return message.warning(t("校验失败"));
  }
  const { success } = await (props.model?.localeId ? update : add)(modelRef);
  if (success) {
    message.success(props.model?.localeId ? t("修改成功") : t("新增成功"));
    emit("ok");
    emit("cancel");
  }
};
</script>
